import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import axios from 'axios';
import { setLoading } from './uiSlice';

// Types
interface PatternProgress {
  _id: string;
  name: string;
  category: string;
}

interface Statistics {
  beginner: {
    completed: number;
    total: number;
    percentage: number;
  };
  intermediate: {
    completed: number;
    total: number;
    percentage: number;
  };
  advanced: {
    completed: number;
    total: number;
    percentage: number;
  };
}

interface OverallProgress {
  currentLevel: 'beginner' | 'intermediate' | 'advanced';
  currentPattern: PatternProgress | null;
  completedPatterns: {
    beginner: PatternProgress[];
    intermediate: PatternProgress[];
    advanced: PatternProgress[];
  };
  statistics: Statistics;
  achievements: string[];
  canLevelUp: boolean;
  nextLevel: 'intermediate' | 'advanced' | null;
  hasGraduated: boolean;
  allPatterns: PatternProgress[];
}

interface ChallengeProgress {
  _id: string;
  user: string;
  challenge: {
    _id: string;
    title: string;
    description: string;
    level: 'beginner' | 'intermediate' | 'advanced';
  };
  pattern: string;
  level: 'beginner' | 'intermediate' | 'advanced';
  status: 'not_started' | 'in_progress' | 'submitted' | 'completed';
  attempts: number;
  lastSubmission: {
    code: string;
    submittedAt: string;
  };
  evaluation: {
    rating: 'Unsatisfactory' | 'Satisfactory' | 'Good' | 'Excellent';
    feedback: string;
    suggestions: string;
    correctPatternUsage: boolean;
    evaluatedAt: string;
  };
  completed: boolean;
  completedAt: string;
}

interface UserStats {
  challenges: {
    total: number;
    completed: number;
    completion: number;
  };
  attempts: {
    total: number;
    average: number;
  };
  ratings: {
    Unsatisfactory: number;
    Satisfactory: number;
    Good: number;
    Excellent: number;
  };
  time: {
    total: number;
    average: number;
  };
}

interface ProgressState {
  overallProgress: OverallProgress | null;
  patternProgress: ChallengeProgress[];
  statistics: UserStats | null;
  loading: boolean;
  error: string | null;
}

const initialState: ProgressState = {
  overallProgress: null,
  patternProgress: [],
  statistics: null,
  loading: false,
  error: null
};

// Get overall progress
export const getOverallProgress = createAsyncThunk(
  'progress/getOverallProgress',
  async (_, { rejectWithValue }) => {
    try {
      const token = localStorage.getItem('token');
      
      if (!token) {
        return rejectWithValue('No token');
      }
      
      const config = {
        headers: {
          'x-auth-token': token
        }
      };
      
      const res = await axios.get('/api/progress', config);
      return res.data;
    } catch (err: any) {
      return rejectWithValue(err.response?.data?.msg || 'Server Error');
    }
  }
);

// 其他异步函数保持不变...

// Reset user progress to beginner level
export const resetToBeginnerLevel = createAsyncThunk(
  'progress/resetToBeginnerLevel',
  async (_, { dispatch, rejectWithValue }) => {
    try {
      dispatch(setLoading({ key: 'progress', value: true }));
      
      const token = localStorage.getItem('token');
      
      if (!token) {
        return rejectWithValue('No token');
      }
      
      const config = {
        headers: {
          'Content-Type': 'application/json',
          'x-auth-token': token
        }
      };
      
      const res = await axios.put('/api/progress/reset-to-beginner', {}, config);
      dispatch(setLoading({ key: 'progress', value: false }));
      return res.data;
    } catch (err: any) {
      dispatch(setLoading({ key: 'progress', value: false }));
      return rejectWithValue(err.response?.data?.msg || 'Server Error');
    }
  }
);

const progressSlice = createSlice({
  name: 'progress',
  initialState,
  reducers: {
    clearProgressError: (state) => {
      state.error = null;
    }
  },
  extraReducers: (builder) => {
    builder
      // Get overall progress
      .addCase(getOverallProgress.pending, (state) => {
        state.loading = true;
      })
      .addCase(getOverallProgress.fulfilled, (state, action: PayloadAction<OverallProgress>) => {
        state.loading = false;
        state.overallProgress = action.payload;
      })
      .addCase(getOverallProgress.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
      
      // 其他case保持不变...
      
      // Reset to beginner level
      .addCase(resetToBeginnerLevel.pending, (state) => {
        state.loading = true;
      })
      .addCase(resetToBeginnerLevel.fulfilled, (state, action) => {
        state.loading = false;
        // 当重置为初学者级别成功后，更新整体进度信息
        if (state.overallProgress) {
          // 更新用户级别为beginner
          state.overallProgress.currentLevel = 'beginner';
          state.overallProgress.nextLevel = 'intermediate';
          state.overallProgress.canLevelUp = false;
          // 清空所有已完成的模式
          state.overallProgress.completedPatterns = {
            beginner: [],
            intermediate: [],
            advanced: []
          };
          // 设置当前模式为null
          state.overallProgress.currentPattern = null;
          // 更新统计信息
          if (state.overallProgress.statistics) {
            Object.keys(state.overallProgress.statistics).forEach(level => {
              state.overallProgress!.statistics[level as keyof Statistics] = {
                completed: 0,
                total: 23,
                percentage: 0
              };
            });
          }
        }
      })
      .addCase(resetToBeginnerLevel.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  }
});

export const { clearProgressError } = progressSlice.actions;

export default progressSlice.reducer; 